import { defineEventHandler,readBody } from 'h3'

export default defineEventHandler(async (event) => {
  const body = await readBody(event)
  const url = (body && body.url) ? String(body.url).trim() : ''

  if (!url) {
    return {
      error: 'missing url'
    }
  }

  try {
    // Fetch the page HTML server-side
    const res = await $fetch(url, { method: 'GET', responseType: 'text' })
    const html = String(res)

    const images = new Set<string>()

    // Match <img ... src=... and common lazy attributes
    const imgAttrRegex = /<img[^>]+(?:src|data-src|data-lazy|data-original)=["']?([^"'\s>]+)["']?/ig
    let m: RegExpExecArray | null
    while ((m = imgAttrRegex.exec(html)) !== null) {
      try {
        const u = new URL(m[1], url).href
        // only accept likely image urls (common extensions or data urls)
        if (/^data:image\//i.test(u) || /\.(jpe?g|png|gif|webp|svg|bmp|avif)(\?.*)?$/i.test(u)) {
          images.add(u)
        }
      } catch (e) {
        // ignore invalid URLs
      }
    }

    // Match CSS url(...) occurrences
    const cssUrlRegex = /url\(["']?([^"')]+)["']?\)/ig
    while ((m = cssUrlRegex.exec(html)) !== null) {
      try {
        const u = new URL(m[1], url).href
        if (/^data:image\//i.test(u) || /\.(jpe?g|png|gif|webp|svg|bmp|avif)(\?.*)?$/i.test(u)) {
          images.add(u)
        }
      } catch (e) {
        // ignore
      }
    }

    // Also try to capture data-srcset or srcset (take first candidate)
    const srcsetRegex = /(?:srcset|data-srcset)=["']?([^"'>]+)["']?/ig
    while ((m = srcsetRegex.exec(html)) !== null) {
      const srcset = m[1]
      const parts = srcset.split(',').map(p => p.trim())
      if (parts.length) {
        const first = parts[0].split(' ')[0]
        try {
          const u = new URL(first, url).href
          if (/^data:image\//i.test(u) || /\.(jpe?g|png|gif|webp|svg|bmp|avif)(\?.*)?$/i.test(u)) {
            images.add(u)
          }
        } catch (e) {}
      }
    }

    // Limit to a reasonable number to avoid huge responses
    const list = Array.from(images).slice(0, 500)

    return {
      url,
      count: list.length,
      images: list
    }
  } catch (err: any) {
    return {
      error: String(err && err.message ? err.message : err)
    }
  }
})
